import { px2rpx } from '../../utils/utils.js'
// 记录滑块开始的点
let startPoint;
// 滑块范围
const blockMin = -15; // 向左偏移 15 个单位
const blockMax = 200 - 15;
const blockRange = blockMax - blockMin;

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    currentValue: {
      type: Number,
      value: 0
    },
    minValue: {
      type: Number,
      value: 0
    },
    maxValue: {
      type: Number,
      value: 100
    },
    canSlide: {
      type: Boolean,
      value: true
    },
    blockImg:{
      type: String,
      value: "images/slider-block.png"
    },
    textSize:{
      type: String,
      value: "20rpx",
    },
    fontWeight:{
      type: Number,
      value: 700,
    },
    color:{
      type: String,
      value: "#333333",
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    blockLeft: 0,
    value: 0,
    valueText: 0,
  },
  lifetimes: {
    attached: function() {
      if (this.properties.currentValue < this.properties.minValue) {
        this.properties.currentValue = this.properties.minValue;
      }
      // 在组件实例进入页面节点树时执行
      this.setData({
        valueText: (this.properties.currentValue).toFixed(0),
        blockLeft: this.properties.currentValue * blockRange / this.properties.maxValue + blockMin,
        value: this.properties.currentValue * blockRange / this.properties.maxValue
      })
    }
  },
  observers: {
    'valueText': function(valueText) {
      // 在 valueText 被修改时, 触发 change 事件
      this.triggerEvent('change', {
        value: parseInt(valueText)
      });
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    blockStart: function(e) {
      startPoint = e.touches[0]
    },
    blockMove: function(e) {
      if (!this.properties.canSlide) {
        return
      }
      // 滑块移动终点
      let endPoint = e.touches[e.touches.length - 1];

      // 水平方向偏移量（转换为 rpx 单位）
      let translateX = px2rpx(endPoint.clientX - startPoint.clientX);

      startPoint = endPoint;
      
      // 计算滑块位置
      let blockLeft = this.data.blockLeft + translateX;

      if (blockLeft > blockMax) {
        return
      }
      // 滑块不能小于最小值
      if (blockLeft < blockMin + this.properties.minValue * blockRange / this.properties.maxValue) {
        return
      }

      let data = {
        blockLeft: blockLeft,
        value: blockLeft - blockMin
      };
      let valueText = ((blockLeft - blockMin) / blockRange * this.properties.maxValue).toFixed(0);
      if (valueText !== this.data.valueText) { // 如果 valueText 有改动, 则触发 valueText 的 set
        data.valueText = valueText
      }
      this.setData(data);
    }
  }
})
